from utils import column_letter_to_index
import pandas as pd
import semopy

# 自变量（IV）,中介变量（MV）, 因变量（DV）
def SEM_w_sempoy(IV_aph,MV_aph,DV_aph):
    ##------------数据预处理--------------
    
    df_EHL = df.iloc[:, IV_aph]
    df_ISH = df.iloc[:, MV_aph]
    df_PCS = df.iloc[:, DV_aph]

    columns_to_extract = {
        df.columns[IV_aph]: 'IV',
        df.columns[MV_aph]: 'MV',
        df.columns[DV_aph]: 'DV'
    }
    processed_df = df[list(columns_to_extract.keys())].rename(columns=columns_to_extract)

    # 定义模型规格，这里使用的是SEM语法
    model_spec = """
    # 路径方程
    DV ~ IV + MV
    MV ~ IV
    """
    # 实例化并估计模型
    model = semopy.Model(model_spec)
    res = model.fit(processed_df)

    # 输出模型的估计结果和拟合指标
    params = model.inspect()
    # print(params)

    # fit_stats = None
    if hasattr(model, 'last_result'):
        fit_stats = model.last_result
        # 打印拟合优度信息
        # print(fit_stats)
    return res,params,fit_stats


if __name__=='__main__':

    data_path = '../data/raw_data/334份 按选项序号 汇总变量后.xlsx'
    df = pd.read_excel(data_path)

    IV_list = ['AT']
    MV_list = ['AU','AV','AW']
    # MV_list = ['AU']
    DV_list = ['CG','CH','CI']

    for IV_ in IV_list:
        for MV_ in MV_list:
            for DV_ in DV_list:
                IV_index = column_letter_to_index(IV_)
                MV_index = column_letter_to_index(MV_)
                DV_index = column_letter_to_index(DV_)
                file_name = '../output/SEM_semopy/'+'IV_{}_MV_{}_DV_{}.txt'.format(IV_index,MV_index,DV_index)
                writer = open(file_name,'w',encoding='utf-8')

                writer.write('自变量 {} \n'.format(str(df.columns[IV_index])))
                writer.write('中介变量 {} \n'.format(str(df.columns[MV_index])))
                writer.write('因变量 {} \n'.format(str(df.columns[DV_index])))

                res,params,fit_stats = SEM_w_sempoy(IV_index,MV_index,DV_index)
                writer.write('---------------------results---------------------: \n')
                writer.write(str(res))
                writer.write('params: \n')
                writer.write(str(params))
                writer.write(' \n')
                if fit_stats is not None:
                    writer.write('---------------------fit_stats---------------------: \n')
                    writer.write(str(fit_stats))
                writer.write('\n---------------------chatGPT分析结果---------------------: \n')
                writer.close()

                # break
            # break
        # break








                


